import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import Select, { Option } from '@kuiper-components/select';
import Input from '@kuiper-components/input';
import Button from '@kuiper-components/button';
import { withRouter } from 'react-router';

import { Search24 as SearchIcon } from '@carbon/icons-react';
import Table, { searchStringBuilder } from '@kuiper-components/page-table';
import { datetime } from '../../../../../common/formatter';
import CopyBoard from '../../../../components/CopyBoard';
import ChartTitle from '../../../../components/ChartTitle';
import {
	WARN_LEVEL_MAP,
	SECURITY_EVENT_TYPE_MAP,
} from '../../../../../common/constants';
import s from './style.module.css';

const STATUS_ARR = ['已处理', '已忽略', '待处理'];

function handleTableFilter({ data, filter }) {
	const filterArr = Object.entries(filter);
	const res = data.filter(row => {
		return filterArr.every(([key, val]) => {
			if (key === 'target') {
				return (
					row[key]?.toLowerCase()?.indexOf(val?.trim()?.toLowerCase()) > -1
				);
			}
			return val === row[key].toString() || val === '';
		});
	});
	return res;
}

function warningStatsBuilder(warning = {}) {
	let text;
	if (warning.ignoredTime) {
		text = '已忽略';
	} else if (warning.isResolved) {
		text = '已处理';
	} else {
		text = '待处理';
	}
	return text;
}

const columns = [
	{
		title: '时间',
		dataIndex: 'datetime',
		key: 'datetime',
		render(date) {
			return <span>{datetime(date)}</span>;
		},
	},
	{
		title: '风险地址',
		dataIndex: 'target',
		key: 'target',
		width: 480,
		render(target) {
			return <CopyBoard className={s.target} text={target} />;
		},
	},
	{
		title: '安全事件',
		dataIndex: 'category',
		key: 'category',
		render(cate) {
			return <span>{SECURITY_EVENT_TYPE_MAP[cate]}</span>;
		},
	},
	{
		title: '威胁等级',
		dataIndex: 'level',
		key: 'level',
		render(level) {
			return <span>{WARN_LEVEL_MAP[level]}</span>;
		},
	},
	// {
	// 	title: '状态',
	// 	dataIndex: 'status',
	// 	key: 'status',
	// 	width: '5rem',
	// 	render(status) {
	// 		return (
	// 			<span className={cn({ [s.warning]: status === '待处理' })}>
	// 				{status}
	// 			</span>
	// 		);
	// 	},
	// },
];
function EventDetail({
	className,
	location,
	history,
	tasks,
	match: {
		path,
		params: { jobId },
	},
	detectTime,
	result,
	prevResult,
	getDropdownRef,
}) {
	const routePrefix = path
		.replace(':taskCategory?', 'securityEvent')
		.replace(':jobId', jobId);
	const search = new URLSearchParams(location.search);
	const filter = JSON.parse(
		decodeURIComponent(search.get('filter') || '') || '{}'
	);

	const [target, setTarget] = React.useState(filter?.target);

	const tableData = React.useMemo(() => {
		const dataArr = tasks.reduce((arr, task) => {
			const warnings = task?.result?.warnings || [];
			warnings.forEach(w => {
				arr.push({
					datetime: task?.endTime,
					target: w?.affects,
					category: w?.category,
					level: w.level,
					status: warningStatsBuilder(w),
					id: w?.id,
				});
			});
			return arr;
		}, []);
		return dataArr.sort((a, b) => {
			return a.level > b.level ? -1 : 1;
		});
	}, [tasks, detectTime]);

	const onFilterChange = params => {
		const search = searchStringBuilder(location.search, {
			filter: JSON.stringify(params),
			page: 1,
			sort: '_ID_DESC',
		});
		history.replace(`${routePrefix}?${search}`);
	};

	const handleTargetChange = val => {
		if (!val) onFilterChange({ ...filter, target: undefined });
		setTarget(val);
	};

	const handleStatusChange = status => {
		onFilterChange({ ...filter, status });
	};

	const handleLevelChange = level => {
		onFilterChange({ ...filter, level });
	};

	const handleCategoryChange = category => {
		onFilterChange({ ...filter, category });
	};

	const handleReset = () => {
		onFilterChange({});
		setTarget('');
	};

	const handleSearch = () => {
		onFilterChange({ ...filter, target });
	};

	return (
		<div className={cn(className, s.eventDetail)}>
			<ChartTitle>安全事件详情</ChartTitle>
			<div className={s.filterContainer}>
				<Input
					type="search"
					placeholder="请输入风险地址"
					className={s.select}
					value={target}
					onChange={handleTargetChange}
					onPressEnter={handleSearch}
					after={<SearchIcon className={s.icon} onClick={handleSearch} />}
				/>
				<div className={s.selectContainer}>
					<Select
						placeholder="请选择安全事件"
						value={filter?.category}
						className={s.select}
						onChange={handleCategoryChange}
						getPopupContainer={getDropdownRef}
						allowClear
					>
						{Object.entries(SECURITY_EVENT_TYPE_MAP).map(([value, label]) => (
							<Option key={value} value={value}>
								{label}
							</Option>
						))}
					</Select>
					<Select
						placeholder="请选择威胁等级"
						value={filter?.level}
						onChange={handleLevelChange}
						getPopupContainer={getDropdownRef}
						className={s.select}
						allowClear
					>
						{Object.entries(WARN_LEVEL_MAP).map(([level, label]) => (
							<Option key={level} value={level}>
								{label}
							</Option>
						))}
					</Select>
					{/* <Select
						placeholder="请选择事件安全状态"
						className={s.select}
						value={filter?.status}
						onChange={handleStatusChange}
						getPopupContainer={getDropdownRef}
						allowClear
					>
						{STATUS_ARR.map(s => (
							<Option key={s} value={s}>
								{s}
							</Option>
						))}
					</Select> */}

					<Button onClick={handleReset}>重置</Button>
				</div>
			</div>
			<Table
				className={cn(s.table, 'tableFormat')}
				type="local"
				routePrefix={routePrefix}
				columns={columns}
				data={tableData}
				onFilter={handleTableFilter}
			/>
		</div>
	);
}

EventDetail.propTypes = {
	className: PropTypes.string,
	match: PropTypes.shape({
		path: PropTypes.string.isRequired,
		params: PropTypes.shape({
			jobId: PropTypes.string,
		}),
	}),
	location: PropTypes.shape({
		search: PropTypes.string,
	}),
	history: PropTypes.object,
	tasks: PropTypes.arrayOf(
		PropTypes.shape({
			_id: PropTypes.string,
			endTime: PropTypes.object,
			result: PropTypes.shape({
				warnings: PropTypes.shape({
					id: PropTypes.string,
				}),
			}),
		})
	),
	getDropdownRef: PropTypes.func,
	result: PropTypes.shape({
		target: PropTypes.string,
		result: PropTypes.shape({
			warningCount: PropTypes.number,
			warnings: PropTypes.shape({
				category: PropTypes.string,
				affects: PropTypes.string,
				detail: PropTypes.object,
			}),
		}),
	}),
	prevResult: PropTypes.shape({
		target: PropTypes.string,
		result: PropTypes.shape({
			warningCount: PropTypes.number,
			warnings: PropTypes.shape({
				category: PropTypes.string,
				affects: PropTypes.string,
				detail: PropTypes.object,
			}),
		}),
	}),
	detectTime: PropTypes.string,
};
EventDetail.defaultProps = {
	className: '',
};

export default withRouter(EventDetail);
